package com.web709.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.web709.common.R;
import com.web709.entity.Admin;
import com.web709.service.AdminService;
import com.web709.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.DataInput;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@Api(tags = "管理员相关接口")
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    @ApiOperation(value = "管理员登录", notes = "根据用户名和密码登录，参数格式：{\n" +
            "    \"username\": \"admin\",\n" +
            "    \"password\": \"123456\"\n" +
            "}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    public R<String> login(HttpServletRequest request, @RequestBody Admin admin) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        String password = admin.getPassword();
        // 使用BCryptPasswordEncoder进行密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        queryWrapper.eq(Admin::getUsername, admin.getUsername());
        queryWrapper.eq(Admin::getPassword, password);
        Admin a = adminService.getOne(queryWrapper);
        if (a == null) {
            // 添加日志记录
            log.warn("登录失败: 用户名或密码错误, 用户名: {}", admin.getUsername());
            return R.error("用户名或密码错误");
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", a.getId());
        claims.put("username", admin.getUsername());
        claims.put("avatar", a.getAvatar());
        claims.put("name", a.getName());
        // 生成JWT令牌
        String token = JwtUtils.generateJwt(claims);
        // 添加日志记录
        log.info("登录成功: 用户名: {}", admin.getUsername());
        return R.success(token);
    }


   @PutMapping("/update")
    @ApiOperation(value = "修改管理员信息", notes = "修改管理员信息,参数格式：{\n" +
            "    \"id\": 1,\n" +
            "    \"username\": \"admin\",\n" +
            "    \"password\": \"<PASSWORD>\",\n" +
            "    \"name\": \"管理员\",\n" +
            "    \"avatar\": \"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif\"\n" +
            "}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "admin", value = "管理员信息", required = true, dataType = "Admin"),
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<String> update(@RequestBody Admin admin, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer userId = (Integer) claims.get("id");

        LambdaUpdateWrapper<Admin> wrapper = new LambdaUpdateWrapper<Admin>()
            .eq(Admin::getId, userId)
            .set(admin.getUsername() != null, Admin::getUsername, admin.getUsername())
            .set(admin.getName() != null, Admin::getName, admin.getName())
            .set(admin.getAvatar() != null, Admin::getAvatar, admin.getAvatar());

        if (admin.getPassword() != null) {
            String encryptedPwd = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
            wrapper.set(Admin::getPassword, encryptedPwd);
        }

        boolean updated = adminService.update(wrapper);
        return updated ? R.success("修改成功") : R.error("修改失败");
    }


    // 获取管理员信息
    @GetMapping("/get")
    @ApiOperation(value = "获取管理员信息", notes = "获取管理员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    })
    public R<Admin> get(HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer userId = (Integer) claims.get("id");
        Admin admin = adminService.getById(userId);
        return R.success(admin);

    }


}
